<?php
/**
 * 支付页面
 */
namespace PayCenter\Controller;
use Common\Model\UserModel;
use PayCenter\BaseController;
use Common\Model\OrderModel;
use Common\Model\EventsModel;
use Common\Model\PointMallModel;
use Common\Model\UtilsModel;
class OrderController extends BaseController {



    //
    public function index(){
        die();
    }

    /**
     * 微信支付
     * Author: shijy
     */
    public function pay(){        
        $id = I("get.id",0,'intval');

        if(!$id) redirect( $_SERVER['HTTP_REFERER'] );//数据为空返回

        $orderInfo = OrderModel::getOrderInfo($id);
        if($orderInfo['status'] == 1){
            if($_SERVER['HTTP_REFERER']) redirect( $_SERVER['HTTP_REFERER'] );//数据为空返回
            else redirect(U('index/index'));
        }

        $orderInfo = $orderInfo['data'];
        if($orderInfo['payTime']){//数据为空返回
            redirect( self::getOrderObjTypeUrl($orderInfo['objType'], $orderInfo['objID'], $orderInfo['id']) );
        }

        $InfoC = OrderModel::$orderTypeInfo[$orderInfo['objType']];
        $uid=$orderInfo['uid'];
        self::$InfoC($orderInfo['objID'],$uid);

        $userInfo = UserModel::getUser($uid);

        $this->smarty->assign('title',C('SITE_NAME'));//$info['data']['title']
        $this->smarty->assign('orderInfo',$orderInfo);
        $this->smarty->assign('userInfo',$userInfo['data']);
        $this->smarty->display("Order_v2/order.html");
    }

    /**
     * 获取活动详情
     */
    private function getEventsInfo($id, $uid){
        $data = EventsModel::getEventsInfo($id, $uid);
        $data = $data['data'];
        $data['imgList'] = $data['imgList'];
        $data['showListTime'] = $data['showListTime'];
        $this->smarty->assign('data',$data);
    }

    private function getPointMallInfo($id, $uid){
        $data = PointMallModel::getDetail($id);
        $data = $data['data'];
        $data['imgList'] = $data['listPic'];
        $typeList = PointMallModel::getDeliveryType();
        $data['deliveryType'] = $typeList[$data['deliveryType']];
        $this->smarty->assign('data',$data);
    }

    /**
     * 检查订单状态
     * User: Rick.Sun.<sunwgjj@126.com>
     * Return: void
     * Address: 浙江宣逸网络科技有限公司
     */
    public function checkOrderStatus(){
        $dataFailure = array('status'=>1,'msg'=>'无效参数');
        $uid = session('uid')+0;
        $id = I("get.id",0,'intval');
        $orderInfo = OrderModel::getOrderInfo($id,$uid);
        $orderInfo = $orderInfo['data'];

        if($orderInfo['payTime']){
            if($orderInfo['objType'] == OBJ_TYPE_ACTIVITY ) {
                if ($orderInfo['point'] > 0) UserModel::minusPoint($uid,-1, $orderInfo['point'], OPT_APPLY_EVENT, "{$orderInfo['objID']}|{$orderInfo['orderTitle']}");
                if ($orderInfo['balance'] > 0) UserModel::minusMoney($uid,-1, $orderInfo['balance'], OPT_APPLY_EVENT, "{$orderInfo['objID']}|{$orderInfo['orderTitle']}");
            }elseif($orderInfo['objType'] == OBJ_TYPE_POINTMALL ){
                if ($orderInfo['point'] > 0) UserModel::minusPoint($uid,-1, $orderInfo['point'], OPT_APPLY_POINTMALL, "{$orderInfo['objID']}|{$orderInfo['orderTitle']}");
                if ($orderInfo['balance'] > 0) UserModel::minusMoney($uid,-1, $orderInfo['balance'], OPT_APPLY_POINTMALL, "{$orderInfo['objID']}|{$orderInfo['orderTitle']}");
            }
            $res = array('status'=>0,'msg'=>'成功');//OrderModel::updateObjStatus($orderInfo);
            $res['url'] = self::getOrderObjTypeUrl($orderInfo['objType'], $orderInfo['objID'],$orderInfo['id']);
        }else{
            $res = $dataFailure;
        }

        $this->ajaxReturn($res);
    }

    /**
     * 获取支付代码 (区分 用户余额|微信支付)
     * User: Rick.Sun.<sunwgjj@126.com>
     * Return: void
     * Address: 浙江宣逸网络科技有限公司
     */
    public function getPay(){
        $dataSuccess = array('status'=>0,'msg'=>'成功');
        $dataFailure = array('status'=>1,'msg'=>'无效参数');

        $uid = I("get.uid",0,'intval');
        $id = I("get.id",0,'intval');
        if(!$uid){
            $dataFailure['msg']='用户编号缺失';
            $this->ajaxReturn($dataFailure);
        }
        $orderInfo = OrderModel::getOrderInfo($id,$uid);
        if($orderInfo['status'] == 1) $this->ajaxReturn($dataFailure);//数据为空返回

        if($orderInfo['data']['payEndTime'] && $orderInfo['data']['payEndTime']<time() ) {
            $dataFailure['msg'] = "支付超时";
            $dataFailure['status'] = 2;
            $this->ajaxReturn($dataFailure);//数据为空返回
        }

        if($orderInfo['data']['payTime']){
            if($orderInfo['objType'] == OBJ_TYPE_ACTIVITY ) {
                if ($orderInfo['point'] > 0) UserModel::minusPoint($uid,-1, $orderInfo['point'], OPT_APPLY_EVENT, "{$orderInfo['objID']}|{$orderInfo['orderTitle']}");
                if ($orderInfo['balance'] > 0) UserModel::minusMoney($uid,-1, $orderInfo['balance'], OPT_APPLY_EVENT, "{$orderInfo['objID']}|{$orderInfo['orderTitle']}");
            }elseif($orderInfo['objType'] == OBJ_TYPE_POINTMALL ){
                if ($orderInfo['point'] > 0) UserModel::minusPoint($uid,-1, $orderInfo['point'], OPT_APPLY_POINTMALL, "{$orderInfo['objID']}|{$orderInfo['orderTitle']}");
                if ($orderInfo['balance'] > 0) UserModel::minusMoney($uid,-1, $orderInfo['balance'], OPT_APPLY_POINTMALL, "{$orderInfo['objID']}|{$orderInfo['orderTitle']}");
            }
            $res = OrderModel::updateObjStatus($orderInfo);
            $res['url'] = self::getOrderObjTypeUrl($orderInfo['objType'], $orderInfo['objID'],$orderInfo['id']);
            $res['status'] = 3;
            $this->ajaxReturn($res);
        }

        $pay_money = I("get.pay_money",0,'float');
        $pay_balance = I("get.pay_balance",0,'intval');
        $orderInfo = OrderModel::updateOrderInfo($id,$uid, array('balance'=>$pay_balance, 'payment'=>$pay_money) );
        //只有余额支付
        if($pay_balance>0 && $pay_money == 0){
            OrderModel::updatePayBalance($id, $uid);
            $res = $dataSuccess;
        }else{
            $dataFailure['msg'] = '必须在微信里面支付';
            if(!session('pay_openid') || !$this->isWechat) $this->ajaxReturn($dataFailure);

            $res = self::getJSApiPay($orderInfo['data'], session('pay_openid'));
        }

        $this->ajaxReturn($res);
    }

    /**
     * 获取 公众号支付 信息
     * User: Rick.Sun.<sunwgjj@126.com>
     * Return: void
     * Address: 浙江宣逸网络科技有限公司
     * @throws \WxPayException
     */
    private function getJSApiPay($orderInfo, $openid){
        $dataSuccess = array('status'=>0,'msg'=>'成功');

        //加载微信类
        require_once WEB_ROOT."/soeLib/wxpay/lib/WxPay.Api.php";
        require_once WEB_ROOT."/soeLib/wxpay/WxPay.JsApiPay.php";

        $tools = new \JsApiPay();
        //必须有OPENID

        $input = new \WxPayUnifiedOrder();
        $input->SetBody($orderInfo['orderTitle']);
        $input->SetAttach($orderInfo['orderTitle']);
        $input->SetOut_trade_no($orderInfo['outTradeNo']);
        $input->SetTotal_fee( intval($orderInfo['pay']*100) );//intval($orderInfo['pay']*100)//默认放一分钱
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 6000));
        $input->SetGoods_tag($orderInfo['orderTitle']);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);

        $order = \WxPayApi::unifiedOrder($input);


        if(strcasecmp($order['return_code'],'SUCCESS')!=0){
            $dataFailure = array('status'=>1,'msg'=>$order['return_msg']);
            return $dataFailure;
        }

        $dataSuccess['data'] = $tools->GetJsApiParameters($order);

        return $dataSuccess;
    }


    /**
     * User: Rick.Sun.<sunwgjj@126.com>
     * Return: string
     * Address: 浙江宣逸网络科技有限公司
     * @param $objType 对象类型
     * @param $objId 对象编号
     * @param $orderId  订单编号
     * @return string
     */
    private function getOrderObjTypeUrl($objType, $objId, $orderId){
        $url = '';
        switch ($objType){
            case OBJ_TYPE_ACTIVITY:
                $url = "../wap.php?m=wap&c=Events&a=info&id=".$objId;
                break;
            case OBJ_TYPE_POINTMALL:
                $url = "../wap.php?m=wap&c=PointMall&a=exchangeLog&payOrderNo=".$orderId;
                break;
        }
        return $url;
    }


}